package com.gdc.miaosha.controller;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.gdc.miaosha.config.UserContext;
import com.gdc.miaosha.entity.User;
import com.gdc.miaosha.exception.GlobalException;
import com.gdc.miaosha.result.CodeMsg;
import com.gdc.miaosha.result.Result;
import com.gdc.miaosha.service.IGoodsService;
import com.gdc.miaosha.util.RedisUtil;
import com.gdc.miaosha.vo.GoodsDetailVO;
import com.gdc.miaosha.vo.GoodsVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.IWebContext;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Objects;

import static com.gdc.miaosha.constants.RedisConstant.*;

/**
 * Description: 商品 Controller
 * @author: gdc
 * @date: 2022/4/4
 * @version 1.0
 */
@Api(value = "商品接口")
@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    /**
     * 商品列表接口，使用了页面缓存
     */
    @ResponseBody
    @RequestMapping(value = "/to_list", produces = "text/html")
    @ApiOperation(value = "跳转到商品列表页面")
    public String list(HttpServletRequest request, HttpServletResponse response, Model model) {
        User user = UserContext.getUser();
        if (Objects.isNull(user)) {
            throw new GlobalException(CodeMsg.SESSION_ERROR);
        }
    	model.addAttribute("user", user);
        // 取页面缓存
        String html = RedisUtil.get(GOODS_LIST_PAGE, String.class);
        if(StrUtil.isNotBlank(html)) {
            return html;
        }

        // 商品列表
        List<GoodsVO> goodsList = goodsService.listGoodsVO();
        model.addAttribute("goodsList", goodsList);
        //return "goods_list";

        IWebContext ctx =new WebContext(request, response,
                request.getServletContext(), request.getLocale(),model.asMap());

        //手动渲染
        html = thymeleafViewResolver.getTemplateEngine().process("goods_list", ctx);
        if(StrUtil.isNotBlank(html)) {
            // 保存页面缓存
            RedisUtil.set(GOODS_LIST_PAGE, html, EXPIRED_1_MINUTE);
        }
        return html;
    }

    /**
     * 商品详情接口，使用了URL页面缓存
     *  网页静态化时，弃用
     */
    @RequestMapping(value="/to_detail2/{goodsId}",produces="text/html")
    @ResponseBody
    @ApiOperation(value = "跳转到商品详情页面")
    public String detail2(HttpServletRequest request, HttpServletResponse response, Model model,
                         @PathVariable("goodsId") Integer goodsId) {
        model.addAttribute("user", UserContext.getUser());

        // 取URL页面缓存
        String html = RedisUtil.get(GOODS_DETAIL_PAGE + goodsId, String.class);
        if(StrUtil.isNotBlank(html)) {
            return html;
        }

        // 获取商品详情
        GoodsVO goodsVO = goodsService.getGoodsVoById(goodsId);
        model.addAttribute("goods", goodsVO);

        int miaoshaStatus;
        long remainSeconds;
        if (LocalDateTime.now().isBefore(goodsVO.getStartDate())) {             //秒杀还没开始，倒计时
            miaoshaStatus = 0;
            remainSeconds = LocalDateTimeUtil.between(goodsVO.getStartDate(), LocalDateTime.now(), ChronoUnit.SECONDS);
        } else if (LocalDateTime.now().isAfter(goodsVO.getEndDate())) {         //秒杀已经结束
            miaoshaStatus = 2;
            remainSeconds = -1;
        } else {                                                                //秒杀进行中
            miaoshaStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("miaoshaStatus", miaoshaStatus);       // 秒杀状态
        model.addAttribute("remainSeconds", remainSeconds);       // 剩余秒杀
        //return "goods_detail";

        IWebContext ctx =new WebContext(request, response,
                request.getServletContext(), request.getLocale(),model.asMap());

        //手动渲染
        html = thymeleafViewResolver.getTemplateEngine().process("goods_detail", ctx);
        if(StrUtil.isNotBlank(html)) {
            // 保存URL页面缓存（与页面缓存的区别是，添加了唯一标识，即同一页面可以存在多个缓存）
            RedisUtil.set(GOODS_DETAIL_PAGE + goodsId, html, EXPIRED_1_MINUTE);
        }
        return html;
    }

    /**
     * 商品详情接口，使用了 网页静态化 处理
     */
    @RequestMapping(value="/detail/{goodsId}")
    @ResponseBody
    public Result<GoodsDetailVO> detail(@PathVariable("goodsId") Integer goodsId) {
        GoodsVO goods = goodsService.getGoodsVoById(goodsId);

        int miaoshaStatus;
        long remainSeconds;
        if (LocalDateTime.now().isBefore(goods.getStartDate())) {             //秒杀还没开始，倒计时
            miaoshaStatus = 0;
            remainSeconds = LocalDateTimeUtil.between(goods.getStartDate(), LocalDateTime.now(), ChronoUnit.SECONDS);
        } else if (LocalDateTime.now().isAfter(goods.getEndDate())) {         //秒杀已经结束
            miaoshaStatus = 2;
            remainSeconds = -1;
        } else {                                                                //秒杀进行中
            miaoshaStatus = 1;
            remainSeconds = 0;
        }

        GoodsDetailVO result = new GoodsDetailVO()
                .setGoods(goods)
                .setUser(UserContext.getUser())
                .setRemainSeconds(remainSeconds)
                .setMiaoshaStatus(miaoshaStatus);
        return Result.success(result);
    }
    
}
